//
//  SAChangePhoneViewController.m
//  SunOn
//
//  Created by RazeenCheng on 2017/5/4.
//  Copyright © 2017年 NeoZhang. All rights reserved.
//

#import "SAChangePhoneViewController.h"

@interface SAChangePhoneViewController ()

@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *verifyTextField;

// 获取验证码
@property (weak, nonatomic) IBOutlet UIView *verifyView;
@property (weak, nonatomic) IBOutlet UILabel *verifyLabel;
@property (weak, nonatomic) IBOutlet UIButton *verifyButton;


@property (nonatomic, strong) NSTimer *countDownTimer; // 倒计时定时器
@property (nonatomic, assign) NSInteger countDownValue; // 倒计时数值

@end

@implementation SAChangePhoneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.verifyView.layer.borderColor = [[UIColor colorWithHexString:@"0D88E8"] CGColor];
    self.verifyView.layer.borderWidth = 1;
    
    self.countDownValue = 60;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [self stopCountDownTimer];
}


#pragma mark - 定时器
- (NSTimer *)countDownTimer
{
    if (!_countDownTimer) {
        _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
    }
    return _countDownTimer;
}

- (void)countDownAction
{
    self.countDownValue--;
    self.verifyLabel.text = [NSString stringWithFormat:@"(%ld)重新获取",(long)self.countDownValue];
    
    if (self.countDownValue == 0) {
        //
        [self stopCountDownTimer];
        self.verifyLabel.text = @"验证码";
    }
}

- (void)startCountDownTimer
{
    [self.countDownTimer fire];
    self.verifyButton.userInteractionEnabled = NO;
}

- (void)stopCountDownTimer
{
    [self.countDownTimer invalidate];
    self.countDownTimer = nil;
    self.verifyButton.userInteractionEnabled = YES;
    self.countDownValue = 60;
}






- (IBAction)getVerifyAction:(id)sender
{
    NSString *phoneString = self.phoneTextField.text;
    
    if (!phoneString || [phoneString isEqualToString:@""]) {
        // 请输入手机号码
        return;
    }
    
    if (phoneString.length != 11) {
        // 请输入正确的手机号码
        return;
    }
    
    [self startCountDownTimer];
}


- (IBAction)confirmAction:(id)sender
{
    [self performSelector:@selector(backAction) withObject:nil afterDelay:1];
}

- (void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if ([self.phoneTextField isFirstResponder]) {
        [self.phoneTextField resignFirstResponder];
    }
    
    if ([self.verifyTextField isFirstResponder]) {
        [self.verifyTextField resignFirstResponder];
    }
}




@end
